package us.codecraft.webmagic.core.downloader.okhttp;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.core.Page;
import us.codecraft.webmagic.core.Request;
import us.codecraft.webmagic.core.Task;
import us.codecraft.webmagic.core.XSpider;
import us.codecraft.webmagic.core.selector.PlainText;

import java.io.IOException;

/**
 * @author <p><a>fishlikewater@126.com</a></p>
 * @date 2019年08月11日 16:29
 * @since
 **/

public class OkhttpCallback implements Callback {

    private Logger log = LoggerFactory.getLogger(getClass());

    private Request request;

    private XSpider xSpider;

    public OkhttpCallback(Request request, Task task){
        this.request = request;
        this.xSpider = (XSpider)task;
    }

    @Override
    public void onFailure(Call call, IOException e) {
        xSpider.onError(request);
        xSpider.onDownloaderFail(request);
        log.warn("downloading page fail {}", call.request().url().toString());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Page page = Page.fail();
        if(response.isSuccessful()){
            log.info("okhttp asyncdownloading page success {}", request.getUrl());
            byte[] bytes = response.body().bytes();
            page.setUrl(new PlainText(call.request().url().toString()));
            page.setRequest(request);
            page.setBytes(bytes);
            page.setStatusCode(response.code());
            page.setDownloadSuccess(true);
            page.setRawText(new String(bytes, xSpider.getSite().getCharset()));
            page.setDownloadSuccess(true);
        }
        if (page.isDownloadSuccess()){
            xSpider.onDownloadSuccess(request, page);
        } else {
            xSpider.onDownloaderFail(request);
        }
        xSpider.onSuccess(request);
        xSpider.pageCount().incrementAndGet();
        response.close();
    }
}
